package web

import (
	"bytes"
	"io"
	"net/http"
	"relay-control/lib/utils"
	"relay-control/src/basic/base"
	"strings"
	"time"
)

var orderOn = []byte{0x02, 0x05, 0x00, 0x00, 0xff, 0x00, 0x8c, 0x09}
var orderOff = []byte{0x02, 0x05, 0x00, 0x00, 0x00, 0x00, 0xcd, 0xf9}

func MainPage(request *http.Request, responseW http.ResponseWriter) {
	_, err := responseW.Write(bytes.NewBufferString("bingo").Bytes())
	utils.TryThrow(err)
}

func SendOn(request *http.Request, responseW http.ResponseWriter) {
	args := splitURI(request.RequestURI)
	if args == nil || len(args) == 0 {
		returnMsg(responseW, "failed")
		return
	}
	name := args["name"]
	if name == "" {
		returnMsg(responseW, "failed")
		return
	}
	if sendOrder(base.SerialPortMap[name], orderOn) {
		returnMsg(responseW, "success write")
		go func() {
			time.Sleep(2 * time.Second)
			sendOrder(base.SerialPortMap[name], orderOff)
		}()
		return
	}
	returnMsg(responseW, "failed")
}

func SendOff(request *http.Request, responseW http.ResponseWriter) {
	args := splitURI(request.RequestURI)
	if args == nil || len(args) == 0 {
		returnMsg(responseW, "failed")
		return
	}
	name := args["name"]
	if name == "" {
		returnMsg(responseW, "failed")
		return
	}
	if sendOrder(base.SerialPortMap[name], orderOff) {
		returnMsg(responseW, "success write")
	} else {
		returnMsg(responseW, "failed")
	}
}

func sendOrder(w io.ReadWriteCloser, order []byte) bool {
	if w == nil {
		println(" - port writer is nil")
		return false
	}
	write, err := w.Write(order)
	println("write : ", write, " and err is : ", err)
	utils.TryThrow(err)
	if write == 8 {
		return true
	}
	return false
}

func returnMsg(responseW http.ResponseWriter, msg string) {
	_, err := responseW.Write(bytes.NewBufferString(msg).Bytes())
	utils.TryThrow(err)
}

func splitURI(origin string) map[string]string {
	if strings.Contains(origin, "?") {
		origin = strings.Split(origin, "?")[1]
		args := strings.Split(origin, "&")
		argsMap := make(map[string]string)
		for i := range args {
			arg := strings.Split(args[i], "=")
			argsMap[arg[0]] = arg[1]
		}
		return argsMap
	}
	return nil
}
